package de.fuberlin.inf.alp2;

import javax.management.InvalidAttributeValueException;
import de.fuberlin.inf.alp2.utils.*;

/**
 * This class has been implemented within the scope of the third exercise of
 * the lecture <i>"Algorithmen und Programmierung 2 - Objektorientierte
 * Programmierung"</i>.
 * @author stefanr
 */
public class Windchill {

	/**
	 * @param args (If the first two arguments contains doubles, they will be
	 * used as temperature and wind velocity. Otherwise the program will ask you
	 * to enter the values.
	 */
	public static void main(String[] args) {
		double[] parameters = Windchill.getParameters(args);
		
		try {
			System.out.println("Windchill-Temperature: " + 
					Windchill.getWindchillTemperature(parameters[0],
					parameters[1]) + "°C");
		}
		catch (InvalidAttributeValueException exc) {
			System.out.println("Invalid argument values.");
		}
	}
	
	/**
	 * This method will use the first two parameters to convert them to double.
	 * If this is not possible, it requests inputs by the user, until the
	 * entered strings has been successfully converted to double.
	 * @param args If the first two arguments contains doubles, they will be
	 * used as temperature and wind velocity. Otherwise the program will ask you
	 * to enter the values again.
	 * @return An array with two doubles (temperature and wind velocity).
	 */
	private static double[] getParameters(String[] args) {
		double[] parameters = new double[2];
		parameters[0] = 10.0;
		parameters[1] = 0.0;
		
		if (args.length > 1) {
			// If temperature and wind speed values are passed with the program
			// arguments, take them
			try {
				parameters[0] = Double.parseDouble(args[0]);
				parameters[1] = Double.parseDouble(args[1]);
			}
			catch (NumberFormatException exc) { }
		} // args.length > 0
		while (-50 >= parameters[0] || 5 <= parameters[0])
			parameters[0] = ConsoleInput.readDouble("Please enter the " +
					"temperature (-50 < t < 5°C)", "Entered value is invalid.");
		while (3 >= parameters[1])
			parameters[1] = ConsoleInput.readDouble("Please enter the wind " +
					"velocity (more than 3 km/h)", "Entered value is invalid.");
		
		return parameters;
	} // getParameters
	
	/**
	 * This method will calculate the windchill temperature corresponding to the
	 * formula of the national weather service.
	 * @param temperature
	 * @param windspeed
	 * @return the computed windchill temperature
	 * @throws InvalidAttributeValueException, if temperatur ist less than -50
	 * or greater than 5 degree celsius or when the wind velocity is less than 3
	 * km/h.
	 */
	private static double getWindchillTemperature(double temperature, double
			windspeed) throws InvalidAttributeValueException {
		if (windspeed < 3.0 || temperature > 5.0 || temperature < -50.0)
			throw new InvalidAttributeValueException();
		double v = Math.pow(windspeed, 0.16);
		return Math.round((13.12 + 0.6215*temperature-
				11.37*v+0.3965*temperature*v)*100.0)/100.0;
	}
}